package com.uaf.aes.advice;

import com.uaf.aes.annotation.AesSecurity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author cailu
 * @filename DecodeRequestAdvice
 * @description 请求数据解密
 * @date 2020/5/6 14:34
 */

@ControllerAdvice(basePackages = "com.uaf.aes.contoller")
public class DecodeRequestAdvice implements RequestBodyAdvice {

	private Logger logger = LoggerFactory.getLogger(this.getClass());


	@Override
	public boolean supports(MethodParameter methodParameter, Type type,
	                        Class<? extends HttpMessageConverter<?>> aClass) {
		return true;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter,
	                                       Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
		try {
			boolean encode = false;
			if (methodParameter.getMethod().isAnnotationPresent(AesSecurity.class)) {
				//获取注解配置的包含和去除字段
				AesSecurity serializedField = methodParameter.getMethodAnnotation(AesSecurity.class);
				//入参是否需要解密
				encode = serializedField.inDecode();
			}
			if (encode) {
				logger.info("对方法method :【" + methodParameter.getMethod().getName() + "】入参数据进行解密");
				return new MyHttpInputMessage(inputMessage);
			} else {
				return inputMessage;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("对方法method :【" + methodParameter.getMethod().getName() + "】入参数据进行解密出现异常：" + e.getMessage());
			return inputMessage;
		}

	}

	@Override
	public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
	                            Type type, Class<? extends HttpMessageConverter<?>> aClass) {
		return body;
	}

	@Override
	public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter,
	                              Type type, Class<? extends HttpMessageConverter<?>> aClass) {
		return true;
	}

}

